﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FurionPearAdmin.VSIXProject.Templates
{
    public class AutoTemplate
    {
        public static readonly string GetSetTemplate = @"
        /// <summary>
        /// {2}
        /// </summary>
        [ExcelColumnName(""{2}"")]
        public {1} {0} { get; set; }
        ";
        public static readonly string UpdateTemplate = @"
            entity.{0}=model.{0};";

        public static readonly string IndexTableTemplate = @"
                    { field: '{0}', title: '@L(""{1}"")' {2}},";
        public static readonly string FromTemplate = @"
         <div class=""layui-form-item"">
              <label class=""layui-form-label"">@L(""{0}"")</label>
              <div class=""layui-input-block"">
                 {1}
              </div>
         </div>";
        public static readonly string FromImgUrlQTemplate = @"
                        $('#{0}Ele_@randomId').attr('src', FileHttpApiUrl+result.Data.{0}); //图片链接（base64）
                        $('#{0}ProgressEle_@randomId').hide();";

        public static readonly string FromImgUrlTemplate = @"
                <input type=""text"" style=""display:none"" id=""{0}InputEle_@randomId"" name=""{0}"" placeholder="""" autocomplete=""off"" class=""layui-input"">
                <div class=""layui-upload"">
                    <button type=""button"" class=""layui-btn"" id=""{0}ButtonEle_@randomId"">@L(""上传图片"")</button>
                    <div class=""layui-upload-list"">
                        <img class=""layui-upload-img"" id=""{0}Ele_@randomId"" style=""height:50px;width:50px"">
                        <p id=""{0}Text_@randomId""></p>
                    </div>
                    <div style=""width: 95px;"" id=""{0}ProgressEle_@randomId"">
                        <div class=""layui-progress layui-progress-big"" lay-showpercent=""yes"" lay-filter=""{0}Progress_@randomId"">
                            <div class=""layui-progress-bar"" lay-percent=""""></div>
                        </div>
                    </div>
                </div>";

        public static readonly string FromImgUrlJQTemplate = @"
//=================================上传图片Start
                //常规使用 - 普通图片上传
                var upload{0} = upload.render({
                    elem: '#{0}ButtonEle_@randomId'
                   // , url: '/Api/System/Uploadfiles/UserImg' //上传接口
                   , url: 'api/File/UploadFile' //上传接口
                  ,data:{
                              DirectoryName:'AutomaticCodeGeneration'
                  }
                , accept: 'images' //只允许上传图片
                , acceptMime: 'image/*' //只筛选图片
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                            $('#{0}Ele_@randomId').attr('src', result); //图片链接（base64）
                    });
                        $('#{0}ProgressEle_@randomId').show();
                        element.progress('{0}Progress_@randomId', '0%'); //进度条复位
                    layer.msg('@L(""上传中"")', { icon: 16, time: 0 });
                }
                , done: function (res) {
                    //如果上传失败
                    // if (res.code > 0) {
                    //     return layer.msg('上传失败');
                    // }
                    if (res.code == 200) {
                            $(""#{0}InputEle_@randomId"").val(res.data)
                    } else {
                        layer.msg(res.msg);

                    }
                    //上传成功的一些操作
                    //……
                          $('#{0}Text_@randomId').html('<span style=""color: green;"">@L(""上传成功"")</span>'); //置空上传失败的状态
                       $('#{0}ProgressEle_@randomId').hide();

                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#ImgText_@randomId');
                    demoText.html('<span style=""color: #FF5722;"">@L(""上传失败"")</span> <a class=""layui-btn layui-btn-xs demo-reload"">@L(""重试"")</a>');
                    demoText.find('.demo-reload').on('click', function () {
                            upload{0}.upload();
                    });
                }
                //进度条
                , progress: function (n, elem, e) {
                      element.progress('{0}Progress_@randomId', n + '%'); //可配合 layui 进度条元素使用
                    if (n == 100) {
                        layer.msg('@L(""上传完毕"")', { icon: 1 });
                    }
                }
            });";
        
        public static readonly string FromFlieUrlQTemplate = @"
                        $('#{0}Text_@randomId').html('<span>'+result.Data.{0}+'<span>'); //
                        $('#{0}ProgressEle_@randomId').hide();
            ";
        public static readonly string FromFlieUrlTemplate = @"
                <input type=""text"" style=""display:none"" id=""{0}InputEle_@randomId"" name=""{0}"" placeholder="""" autocomplete=""off"" class=""layui-input"">
                <div class=""layui-upload"">
                    <button type=""button"" class=""layui-btn"" id=""{0}ButtonEle_@randomId"">@L(""上传文件"")</button>
                    <div class=""layui-upload-list"">
                        <p id=""{0}Text_@randomId""></p>
                    </div>
                    <div style=""width: 95px;"" id=""{0}ProgressEle_@randomId"">
                        <div class=""layui-progress layui-progress-big"" lay-showpercent=""yes"" lay-filter=""{0}Progress_@randomId"">
                             <div class=""layui-progress-bar"" lay-percent=""""></div> 
                        </div>
                    </div>
                </div>";
        public static readonly string FromFlieUrlJQTemplate = @"
//=================================上传文件Start
                         //常规使用 - 普通文件上传
                        var upload{0} = upload.render({
                        elem: '#{0}ButtonEle_@randomId'
                       // , url: '/Api/System/Uploadfiles/UserImg' //上传接口
                       , url: 'api/File/UploadFile' //上传接口
                      ,data:{
                                  DirectoryName:'AutomaticCodeGeneration'
                      }
                       , accept: 'file' 
                    //, acceptMime: 'image/*' //只筛选图片
                    , before: function (obj) {
                        //预读本地文件示例，不支持ie8
                        obj.preview(function (index, file, result) {
                                $('#{0}Ele_@randomId').attr('src', result); //图片链接（base64）
                        });
                            $('#{0}ProgressEle_@randomId').show();
                            element.progress('{0}Progress_@randomId', '0%'); //进度条复位
                        layer.msg('@L(""上传中"")', { icon: 16, time: 0 });
                    }
                    , done: function (res) {
                        //如果上传失败
                        // if (res.code > 0) {
                        //     return layer.msg('上传失败');
                        // }
                        if (res.code == 200) {
                                $(""#{0}InputEle_@randomId"").val(res.data)
                        } else {
                            layer.msg(res.msg);

                        }
                        //上传成功的一些操作
                        //……
                         $('#{0}Text_@randomId').html('<span style=""color: green;"">@L(""上传成功"")</span><span>'+res.data+'<span>'); //置空上传失败的状态
                         $('#{0}ProgressEle_@randomId').hide();

                    }
                    , error: function () {
                        //演示失败状态，并实现重传
                        var demoText = $('#ImgText_@randomId');
                        demoText.html('<span style=""color: #FF5722;"">@L(""上传失败"")</span> <a class=""layui-btn layui-btn-xs demo-reload"">@L(""重试"")</a>');
                        demoText.find('.demo-reload').on('click', function () {
                                    upload{0}.upload();
                        });
                    }
                    //进度条
                    , progress: function (n, elem, e) {
                          element.progress('{0}Progress_@randomId', n + '%'); //可配合 layui 进度条元素使用
                        if (n == 100) {
                            layer.msg('@L(""上传完毕"")', { icon: 1 });
                        }
                    }
                });
                //=============================End";

        public static readonly string FromHtmlUrlQTemplate = @"
                        {0}TinymceEle=initTinymce('{0}Ele_@randomId',"""");";

        public static readonly string FromHtmlUrlTemplate = @"<textarea id=""{0}Ele_@randomId"" name=""{0}""  class=""layui-textarea""></textarea>";

        public static readonly string FromHtmlUrlJQTemplate = @"
//===========================================富文本框
              var OssUrl=""/api/File/UploadFile""
              function initTinymce(id, contectStr) {
                       var TinymceEle = tinymce.render({
                        elem: ""#"" + id
                        , height: 500
                        , width: '100%'
                        , content: contectStr // 设置初始值
                        , images_upload_handler: function (blobInfo, succFun, failFun) {
                            var xhr, formData;
                            var file = blobInfo.blob();//转化为易于理解的file对象
                            xhr = new XMLHttpRequest();
                            xhr.withCredentials = false;
                            xhr.open('POST', OssUrl);
                            xhr.onload = function () {
                                var json;
                                if (xhr.status != 200) {
                                    failFun('HTTP Error: ' + xhr.status);
                                    return;
                                }
                                json = JSON.parse(xhr.responseText);
                                if (json.code != 200) {
                                    failFun('Invalid JSON: ' + xhr.responseText);
                                    return;
                                }
                    
                                succFun(FileHttpApiUrl+ json.data);
                            };
                            formData = new FormData();
                            formData.append('file', file, file.name);//此处与源文档不一样
                            formData.append('DirectoryName','TinymceImg' );//此处与源文档不一样
                            xhr.send(formData);
                        }
                        , init_instance_callback: function (editor) {
                            autoImportImage(editor, 'TinymceImg');
                        }
                    });
                        return TinymceEle;
                }
            //===================富文本框End
        ";

        public static string GetContent(string fileName,string[] arg0)
        {

            string con = GetTxt(fileName);
            return Format(con,arg0);
        }

      

        /// <summary>
        /// 嵌入文件内容获取
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetTxt(string url)
        {
            //获得正在运行类所在的名称空间

            Type type = MethodBase.GetCurrentMethod().DeclaringType;
             string MainUrl = "FurionPearAdmin.VSIXProject.Templates.";

            //取txt文件的内容
            Stream ms = type.Assembly.GetManifestResourceStream(MainUrl + url);

            byte[] bs = new byte[ms.Length];
            ms.Read(bs, 0, bs.Length);

            string txt = Encoding.UTF8.GetString(bs); //将byte数组转换为string.
            return txt;
        }
        /// <summary>
        /// 字符串 处理
        /// </summary>
        /// <param name="format"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static String Format(String format, params string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                format = format.Replace("{" + i + "}", args[i]);
            }
            return format;
        }
    }
}
